package com.hzhc.controller.index;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hzhc.common.BaseController;
import com.hzhc.dto.MemberVo;
import com.hzhc.entity.CompanyInfo;
import com.hzhc.enumBean.ResultUtilCodeEnum;
import com.hzhc.mapper.CompanyInfoMapper;
import com.hzhc.service.UserMemberService;
import com.hzhc.util.EncryptAndDecrypt;
import com.hzhc.utils.HttpsPostUtil;
import com.hzhc.utils.ResultUtil;
import com.hzhc.vo.SsoUserCustomizeVo;
import com.hzhc.vo.SsoUserVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * @ClassName: IndexController
 * @Description:
 * @version 1.0
 * @author: duanhm
 * @Date: 2019/11/23 12:35:11
 * 
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/")
public class IndexController extends BaseController {

	private final UserMemberService userMemberService;

	private final CompanyInfoMapper companyInfoMapper;

	@Value("${SSO.getAppTokenUrl}")
	private String getAppTokenUrl;

	@Value("${SSO.appId}")
	private String appId;

	@Value("${SSO.appSecret}")
	private String appSecret;

	@Value("${SSO.getTokenUrl}")
	private String getTokenUrl;

	@Value("${SSO.grant_type}")
	private String grantType;

	@Value("${SSO.getUserInfoUrl}")
	private String getUserInfoUrl;

	@Value("${SSO.roleId}")
	private Long roleId;
	@Value("${SSO.comCode}")
	private Integer comCode;

	@RequestMapping("/ssoIndex")
	public ResultUtil<MemberVo> ssoIndex(HttpServletRequest request, HttpServletResponse response, Model model, @RequestBody MemberVo memberVo1) throws Exception {
		//getAppToken

		String code =memberVo1.getCode();
		String appToken = "";

		//getTokenResult
		String accessToken = "";
		String refreshToken = "";
		Integer expiresIn = null;
		String tokenType = "";
		String scope = "";

		//getUserInfo
//		JSONObject comCustomize = new JSONObject();
//		JSONObject companyInfo = new JSONObject();

		String comCustomizeStr = "";
		String companyInfoStr = "";
		String userInfoStr = "";

		String msg = "";

		//获取单点登录平台token
//		String url = "https://cs-login.hbgyl.com.cn/prod-api/outside/oauth2/getAppToken";
		//凭借整体发送数据数据
		JSONObject jsonBodyObject = new JSONObject();
		jsonBodyObject.put("appId", appId);
		jsonBodyObject.put("appSecret", appSecret);

		//组装发送头部
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		String resultTokenStr = HttpsPostUtil.sendHttpsPostJSON(getAppTokenUrl, jsonBodyObject, headers);
		JSONObject jsonObject = JSON.parseObject(resultTokenStr);
		if ("200".equals(jsonObject.getString("code"))) {
			JSONObject jsonData = jsonObject.getJSONObject("data");
			appToken = jsonData.getString("app_token");
		} else {
			msg = jsonObject.getString("msg");
		}
		if (StrUtil.isNotBlank(appToken)) {
			//获取单点登录平台Access token
//			String getTokenUrl = "https://cs-login.hbgyl.com.cn/prod-api/outside/oauth2/token";
			//凭借整体发送数据数据
			JSONObject getTokenBody = new JSONObject();
			getTokenBody.put("grant_type", grantType);
			getTokenBody.put("code", code);
			getTokenBody.put("redirect_uri", "");
			//组装发送头部
			HttpHeaders getTokenHeaders = new HttpHeaders();
			getTokenHeaders.setContentType(MediaType.APPLICATION_JSON);
			getTokenHeaders.set("app-token", appToken);
			getTokenHeaders.set("Accept-Certificate", appId);
			String getTokenResult = HttpsPostUtil.sendHttpsPostJSON(getTokenUrl, getTokenBody, getTokenHeaders);
			JSONObject getTokenResultObj = JSON.parseObject(getTokenResult);
			if ("200".equals(getTokenResultObj.getString("code"))) {
				JSONObject jsonTokenData = getTokenResultObj.getJSONObject("data");
				accessToken = jsonTokenData.getString("access_token");
				refreshToken = jsonTokenData.getString("refresh_token");
				expiresIn = jsonTokenData.getIntValue("expires_in");
				tokenType = jsonTokenData.getString("token_type");
				scope = jsonTokenData.getString("scope");
			} else {
				msg = getTokenResultObj.getString("msg");
			}
		}
		if (StrUtil.isNotBlank(accessToken) && StrUtil.isNotBlank(appToken)) {
//			String getUserInfoUrl = "https://cs-login.hbgyl.com.cn/prod-api/outside/oauth2/getUserInfo";
			//组装发送头部
			HttpHeaders getUserInfoHeard = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON);
			getUserInfoHeard.set("app-token", appToken);
			getUserInfoHeard.set("Authorization", accessToken);
			getUserInfoHeard.set("Accept-Certificate", appId);
			logger.info("accessToken====" + accessToken);
			logger.info("appToken====" + appToken);
			logger.info("code====" + code);
			MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
			String getUserInfoResult = HttpsPostUtil.sendRequest(getUserInfoUrl, params, HttpMethod.GET, getUserInfoHeard);
			JSONObject getUserInfoResultObj = JSON.parseObject(getUserInfoResult);
			if ("200".equals(getUserInfoResultObj.getString("code"))) {
				JSONObject userInfoData = getUserInfoResultObj.getJSONObject("data");
				comCustomizeStr = userInfoData.getString("comCustomize");
				companyInfoStr = userInfoData.getString("companyInfo");
				userInfoStr = userInfoData.getString("userInfoStr");
//				comCustomize = userInfoData.getJSONObject("comCustomize");
//				companyInfo = userInfoData.getJSONObject("companyInfo");
				logger.info("userInfoStr====" + userInfoStr);
				logger.info("companyInfoStr====" + companyInfoStr);
				logger.info("comCustomizeStr====" + comCustomizeStr);
				if(StrUtil.isNotBlank(comCustomizeStr)){
					String decryptComCustomizeStr = EncryptAndDecrypt.decrypt(comCustomizeStr, EncryptAndDecrypt.KEY);
					logger.info("decryptComCustomSStr====" + decryptComCustomizeStr);
					JSONObject comCustomizeJson = JSON.parseObject(decryptComCustomizeStr);
				}
				Long companyId = null;
				if(StrUtil.isNotBlank(comCustomizeStr)){
					String decryptCompanyInfoStr = EncryptAndDecrypt.decrypt(companyInfoStr, EncryptAndDecrypt.KEY);
					logger.info("decryptCompanyInfoStr====" + decryptCompanyInfoStr);
					JSONObject companyInfoJson = JSON.parseObject(decryptCompanyInfoStr);
					String comName = companyInfoJson.getString("name");
					if (StrUtil.isBlank(comName)) {
						return ResultUtil.build(400,"账号信息公司名称为空，无法登录！");
					}
					CompanyInfo info = companyInfoMapper.selectOne(Wrappers.<CompanyInfo>lambdaQuery()
							.eq(CompanyInfo::getName, comName)
							.eq(CompanyInfo::getDisable, 0));
					if (info == null) {
						info = new CompanyInfo();
						info.setName(comName).setComCode(comCode.toString())
								.setTelephone(companyInfoJson.getString("phone"))
								.setContacts(companyInfoJson.getString("contract"))
								.setCreateTime(LocalDateTime.now());
						companyInfoMapper.insert(info);
						companyId = info.getId();
					}else{
						companyId = info.getId();
					}
				}else{
					return ResultUtil.build(400,"账号信息公司为空，无法登录！");
				}

				String decryptUserIndoStr = EncryptAndDecrypt.decrypt(userInfoStr, EncryptAndDecrypt.KEY);


				logger.info("decryptUserIndoStr====" + decryptUserIndoStr);

				JSONObject userInfoJson = JSON.parseObject(decryptUserIndoStr);
				JSONObject userInfoJsonData = userInfoJson.getJSONObject("data");
				SsoUserVo ssoUserVo = userInfoJsonData.getObject("userInfo", SsoUserVo.class);
				SsoUserCustomizeVo ssoUserCustomizeVo = userInfoJsonData.getObject("userCustomize", SsoUserCustomizeVo.class);
				String customizeValueJsonStr = ssoUserCustomizeVo.getCustomizeValues();
				logger.info("customizeValueJsonStr====" + customizeValueJsonStr);
				if(StrUtil.isNotBlank(customizeValueJsonStr)){
					JSONObject customizeValueJsonObj = JSON.parseObject(customizeValueJsonStr);
					Long dwfwOldid = customizeValueJsonObj.getLong("dwfw_oldid");
					logger.info("dwfwOldid====" + dwfwOldid);
					ssoUserVo.setDwfwOldid(dwfwOldid);
				}
				ssoUserVo.setAccessToken(accessToken);
				ssoUserVo.setAppToken(appToken);
				ssoUserVo.setCompanyId(companyId);


				MemberVo memberVo = userMemberService.syncUsersAutoLogin(request, ssoUserVo, roleId);
				if (memberVo.getId()!=null) {
					return ResultUtil.build(memberVo, ResultUtilCodeEnum.SUCCESS);
				} else {
					return ResultUtil.build(400,"用户信息不存在，无法登录！");
				}

			} else {
				msg = getUserInfoResultObj.getString("msg");
			}
		}
		if (StrUtil.isNotBlank(msg)) {
			return ResultUtil.build(400,msg);
		}
		return null;
	}
}
